package todo;

import done.AbstractWashingMachine;
import se.lth.cs.realtime.*;

public class SpinController extends PeriodicThread {

	private SpinEvent last_event;
	private AbstractWashingMachine machine;
	private long dirchange_time=0;
	private int dir;

	public SpinController(AbstractWashingMachine mach) {
		super(Sim.time(1000));
		this.machine = mach;
	}

	public void perform() {
		while (!mailbox.isEmpty()) {
			last_event = (SpinEvent)mailbox.tryFetch();
		}
		
		if (last_event == null) return;
		
		switch (last_event.getMode()) {
		case (SpinEvent.SPIN_FAST):
			machine.setSpin(machine.SPIN_FAST);
			break;
			
		case (SpinEvent.SPIN_OFF):
			machine.setSpin(machine.SPIN_OFF);
			break;
			
		case (SpinEvent.SPIN_SLOW):
			if (dirchange_time <= Sim.getTime()) {
				dirchange_time = Sim.getTime(2*60*1000);
				dir = dir==machine.SPIN_LEFT? machine.SPIN_RIGHT: machine.SPIN_LEFT;
				machine.setSpin(dir);
			}
		}
	}
}
